# -*- coding: utf-8 -*-
import os
import sys
import hashlib
from typing import List
from fastapi import FastAPI
from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models

app = FastAPI()


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(access_key_id, access_key_secret) -> bailian20231229Client:
        """
        使用 AK 初始化账号 Client
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret
        )
        # Endpoint 请参考 https://api.aliyun.com/product/bailian
        config.endpoint = f'bailian.cn-beijing.aliyuncs.com'
        return bailian20231229Client(config)

    @staticmethod
    def create_api_info(
        category_id: str,
        workspace_id: str,
    ) -> open_api_models.Params:
        """
        API 相关
        @param path: string Path parameters
        @return: OpenApi.Params
        """
        params = open_api_models.Params(
            # 接口名称,
            action='ApplyFileUploadLease',
            # 接口版本,
            version='2023-12-29',
            # 接口协议,
            protocol='HTTPS',
            # 接口 HTTP 方法,
            method='POST',
            auth_type='AK',
            style='ROA',
            # 接口 PATH,
            pathname=f'/{workspace_id}/datacenter/category/{category_id}',
            # 接口请求体内容格式,
            req_body_type='formData',
            # 接口响应体内容格式,
            body_type='json'
        )
        return params

    @staticmethod
    def call_api(
        access_key_id,
        access_key_secret,
        category_id,
        workspace_id,
        file_name,
        md5,
        size_in_bytes
    ):
        client = Sample.create_client(access_key_id, access_key_secret)
        params = Sample.create_api_info(category_id, workspace_id)
        # body params
        body = {}
        body['FileName'] = file_name
        body['Md5'] = md5
        body['SizeInBytes'] = size_in_bytes
        # runtime options
        runtime = util_models.RuntimeOptions()
        request = open_api_models.OpenApiRequest(
            body=body
        )
        result = client.call_api(params, request, runtime)
        return result


def calculate_file_md5(file_path):
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


@app.get("/apply_file_upload_lease/")
async def apply_file_upload_lease(
    category_id: str = 'cate_65540ce38c47444589480562fe235427_10329720',
    workspace_id: str = 'llm-xdz6ktdnxjthlm1k',
    file_name: str = r"房产资料.docx",
):
    try:
        access_key_id = 'LTAI5tDx6R4kYzFMoLcbARUe'
        access_key_secret = 'uhUHyyua7tiv7hRf2aRNkx6YCGJM4G'
        if not access_key_id or not access_key_secret:
            return {"error": "请设置 ALIYUN_ACCESS_KEY_ID 和 ALIYUN_ACCESS_KEY_SECRET 环境变量"}

        if not os.path.exists(file_name):
            return {"error": f"文件 {file_name} 不存在"}

        size_in_bytes = str(os.path.getsize(file_name))
        md5 = calculate_file_md5(file_name)

        result = Sample.call_api(
            access_key_id,
            access_key_secret,
            category_id,
            workspace_id,
            file_name,
            md5,
            size_in_bytes
        )
        return result
    except FileNotFoundError:
        return {"error": f"文件 {file_name} 未找到"}
    except Exception as e:
        return {"error": str(e)}

    